package com.example.mcdonaldapplication.activity

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Looper
import android.widget.Toast
import com.example.mcdonaldapplication.databinding.ActivityExchangeTicketBinding
import com.example.mcdonaldapplication.info.ServerIP
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import kotlin.concurrent.thread

class ExchangeTicketActivity : AppCompatActivity() {
    private lateinit var binding:ActivityExchangeTicketBinding
    private val serverIp = ServerIP.getIp()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityExchangeTicketBinding.inflate(layoutInflater)
        setContentView(binding.root)
        supportActionBar?.hide()

        val btnExchange = binding.btnExchange
        btnExchange.setOnClickListener{
            val editTicketID = binding.editTicketID.text.toString()
            exchange(editTicketID)
        }
    }

    private fun exchange(tid:String){
        thread {
            val prefs = getSharedPreferences("user", Context.MODE_PRIVATE)
            val uid = prefs.getInt("uid", 0).toString()
            val formBody: FormBody = FormBody.Builder()
                .add("uid", uid)
                .add("tid", tid)
                .build()
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("http://${serverIp}/user/exchangeTicket")
                .post(formBody)
                .build()
            val response = client.newCall(request).execute()
            val responseData = response.body.string()
            parseJsonExchange(responseData)
        }
    }

    private fun parseJsonExchange(jsonData: String) {
        try {
            val jsonObject = JSONObject(jsonData)
            val success = jsonObject.optString("success")

            if(success == "true") {
                Looper.prepare()
                Toast.makeText(this, "兑换成功", Toast.LENGTH_SHORT).show()
                finish()
                Looper.loop()
            }else{
                Looper.prepare()
                Toast.makeText(this, "兑换失败,优惠券不存在", Toast.LENGTH_SHORT).show()
                Looper.loop()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


}